<template>
	<div class="binding-mobile">
		<p class="text-t-3 text-sm pb-5">
			<base-icon name="hint" class="text-[15px]" />
			{{ $t('binding.subtitleMobile') }}
		</p>
		<p class="text-black"></p>
		<account-tel class="mt-[10px]" v-model="mobile" />

		<base-input :label="$t('mobile.code')" v-model="mobileCode" type="code" :error="codeError">
			<template #suffix>
				<base-code
					:type="AccountType.mobile"
					:codeType="CodeType.bindding"
					:disabled="!isMobile(mobile)"
					:nameData="mobile" />
			</template>
		</base-input>
		<div class="pt-5 pb-10">
			<base-button type="primary" :disabled="submitDisabled" :loading="loading" @click="onSubmit">
				{{ $t('action.confirm') }}
			</base-button>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { isCode, isLength, isMobile } from '@/utils/validate'
import { AccountType, CodeType } from '@/enums'
import { setEmailOrMobile } from '@/api/profile.ts'
import { t } from '@/utils'
import { useProfileStore, useWalletStore } from '@/store'
import { HTTP_CODES } from '@/constants'
import AccountTel from '@/components/account/account-tel/index.vue'
import { useMessage } from '@/hooks'
import { BaseButton, BaseIcon, BaseInput, BaseCode } from '@/components/base'

const mobile = ref('')
const mobileCode = ref('')

const validateMobile = computed(
	() =>
		mobile.value &&
		mobile.value.split(' ').length > 1 &&
		mobile.value.split(' ')[1] &&
		!isMobile(mobile.value)
)

const message = useMessage()
const loading = ref(false)

const profileStore = useProfileStore()
const walletStore = useWalletStore()

const submitDisabled = computed(() => validateMobile.value || !isLength(mobileCode.value, 6, 20))
const codeError = computed(() =>
	mobileCode.value && !isCode(mobileCode.value) ? t('error.code') : ''
)

const onSubmit = async () => {
	try {
		loading.value = true
		const params = {
			type: AccountType.mobile,
			codeType: CodeType.bindding,
			nameData: mobile.value,
			code: mobileCode.value
		}
		await setEmailOrMobile(params)
		profileStore.setBindingPopupShow(false)
		loading.value = false
		message.success(t('tip.saveSuccess'))
		await profileStore.getUserInfo()
		if (walletStore.showValidate) {
			walletStore.setWalletDepositShow(true)
		}
		walletStore.setValidateShow(false)
		resetDate()
	} catch (error: any) {
		loading.value = false
		if (error.code === HTTP_CODES.MobileAndEmailAccountExisted) {
			message.error(t('validate.bindEmailExist'))
		} else {
			message.error(error)
		}
	}
}

const resetDate = () => {
	mobile.value = ''
	mobileCode.value = ''
}
</script>

<style lang="scss" scoped></style>
